import requests
import time
import csv
import datetime

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
    'referer': 'http://movie.mtime.com/209164/comment'
}

with open('The Martian_reviews2.0.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(["Review", "Sentiment", "Time"])

    for page in range(1, 30):
        params = {
            'tt': int(time.time() * 1000),
            'movieId': '216036',
            'pageIndex': page,
            'pageSize': 200,
            'orderType': 1
        }
        res = requests.get('http://front-gateway.mtime.com/library/movie/comment.api',
                           headers=headers, params=params)

        comment_lists = res.json()['data']['list']
        time.sleep(15)
        for i in comment_lists:
            review = i['content']
            rating = float(i['rating'])
            review_time = i['commentTime']
            time_str = datetime.datetime.fromtimestamp(review_time).strftime('%Y-%m-%d %H:%M:%S')
            sentiment = '好评' if rating >= 7 else '差评'
            writer.writerow([review, sentiment, time_str])
            print('影评内容:', review)
            print('用户打分:', rating)
            print('评价:', sentiment)
            print('评论时间:', time_str)
